package com.crm.controller.loginController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.crm.dao.UserDAO;
import com.crm.entity.Business;
import com.crm.entity.User;
import com.crm.util.LoggerUtil;

@Controller
@RequestMapping("/business")
public class LoginController {
	protected final Log logger = LogFactory.getLog(getClass());
	@RequestMapping(value="/login.do",method = RequestMethod.POST)
	public ModelAndView login(HttpServletRequest request, ModelAndView model,HttpSession session) {
		System.out.println("Setting uplog  X0002 ");
		System.out.println("hello x0002 ");
		LoggerUtil.setUpLog(null);
		String userid=request.getParameter("user");
		String pass=request.getParameter("pwd");
		UserDAO UDao= new UserDAO();
		System.out.println(" User Name Is:"+userid);
		try {
			
			 User u=UDao.validatCredentials(userid,pass);
			 System.out.println("BusinessUser is "+u);
			 if(u!=null && u.getEmail().trim().length()>0){
				Business business=new Business();
				try {
					business=u.getBusiness();
					logger.info(userid+" succesfully logged in for the company "+business.getBusinessName());
					session.setAttribute("business",business);
					session.setAttribute("user",u);
				} catch (Exception e) {
					e.printStackTrace();
				}			
				
					model.setViewName("redirect:/totalReports/show.do");
								return model;
			}
			else {
				String message="Your Credentials Are Wrong, Please Enter  Valid Credentials";
				System.out.println(userid+" tried to login to the ACRM application");
				model.setViewName("/jsp/index.jsp?error="+message);
				System.out.println("this is else block in login controller");
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return model;

	}
	@RequestMapping(value="/logout")
	public ModelAndView logout(HttpServletRequest request,HttpSession session,ModelAndView model) {
				User user=(User)session.getAttribute("user");
				if(user!=null){
					logger.info(user.getUserName()+" successfully logged out of the ACRM application.");
				}
				session = request.getSession(false);
		        if (session != null) {
		            session.invalidate();
		        }
		        
		        model.setViewName("/jsp/index.jsp");
		return model;
      }
}